const express = require("express");
const router = express.Router();
const multer = require("multer");
const path = require("path");

//随机数
function r(min, max) {
    const dec = max - min;
    return parseInt(Math.random() * dec + min);
}
const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, path.join(__dirname, "../public/upload"))
    },
    filename: function (req, file, cb) {
        const name = Date.now() + "" + r(100000, 1000000) + path.extname(file.originalname);
        cb(null, name)
    }
})
const upload = multer({
    // dest: "public/upload",
    storage: storage,
    fileFilter: function (req, file, cb) {
        //如何得到文件的后缀名
        const ext = path.extname(file.originalname).toLowerCase();//得到文件的后缀名
        const expects = [".jpg", ".png", ".bmp", ".gif", "tiff"];//服务器接受的后缀名
        if (expects.includes(ext)) {
            cb(null, true);
        } else {
            cb(new Error('文件类型不符合！'))
        }

    },
    limits: {
        fileSize: 500 * 1024,  //文件在200kb以内
    }
}).array("imgfile");

router.post("/", (req, res) => {
    upload(req, res, function (err) {
        if (err) {
            // 发生错误
            res.send({
                code: 1,
                message: err.message
            })
        } else {
            // 一切都好  
            res.send({
                code: 0,
                message: "",
                data: req.files.map(item => "/upload/" + item.filename)
            });
        }
    })
})
module.exports = router; 
